from gm.api import *
import numpy as np
import talib


def init(context):
    context.symbol = 'SZSE.300296'
    context.frequency = '1d'
    context.fields = 'open,high,low,close,volume'
    context.ceilingAmt = 60
    context.floorAmt = 20
    context.bolBandTrig = 1

    schedule(schedule_func=algo, date_rule='1d', time_rule='09:30:00')


lookBackDays = 30


def algo(context):
    global lookBackDays
    today = context.now
    last_day = get_previous_trading_date('SZSE', today)

    data = history_n(
        symbol=context.symbol,
        frequency=context.frequency,
        count=int(lookBackDays),
        end_time=last_day,
        fields=context.fields,
        fill_missing='last',
        adjust=ADJUST_PREV,
        df=True
    )

    high = np.asarray((data['high'].values))
    low = np.asarray((data['low'].values))
    close = np.asarray((data['close'].values))
    # open = np.asarray((data['open'].values))

    todayVolatility = np.std(close)
    yesterDayVolatility = np.std(close[:-1])
    deltaVolatility = (todayVolatility - yesterDayVolatility) / todayVolatility

    lookBackDays = np.round(lookBackDays * (1 + deltaVolatility))
    lookBackDays = np.min([lookBackDays, context.ceilingAmt])
    lookBackDays = np.max([lookBackDays, context.floorAmt])

    MidLine = np.average(close)
    Band = np.std(close)
    # print(MidLine, Band, context.bolBandTrig)
    upBand = MidLine + context.bolBandTrig * Band
    lowBand = MidLine - context.bolBandTrig * Band

    buyPoint = np.max(high)
    sellPoint = np.min(low)
    current_data = current(symbols=context.symbol)
    current_price = current_data[0]['price']

    if ((close[-1] > upBand) and (current_price > buyPoint)):
        order_percent(symbol=context.symbol, percent=1, side=OrderSide_Buy,
                      position_effect=PositionEffect_Open, order_type=OrderType_Market, price=0)
    if ((close[-1] < lowBand) and (current_price < sellPoint)):
        order_percent(symbol=context.symbol, percent=0, side=OrderSide_Sell,
                      position_effect=PositionEffect_Open, order_type=OrderType_Market, price=0)


if __name__ == '__main__':
    run(
        strategy_id='a5299b24-8b44-11e9-a4d4-b499baf0193a',
        filename='程序5_13DynamicBreakout策略.py',
        mode=MODE_BACKTEST,
        token='90be3f863b23ab3c1ef68d1f9b8dc06e4bebb30d',
        backtest_start_time='2017-01-01 09:00:00',
        backtest_end_time='2017-12-31 15:00:00',
        backtest_initial_cash=20000,
        backtest_adjust=ADJUST_PREV,
    )
